<template>
    <van-nav-bar title="新闻详情" left-arrow @click-left="router.back()" />
    <div class="container">
        <h1>{{ detail.title }}</h1>
        <div class="desc-info">
            <div>{{ detail.createTime }}</div>
            <div>阅读：{{ detail.views || 0 }}</div>
            <div>收藏：{{ detail.collect || 0 }}</div>
            <div>点赞：{{ detail.likes || 0 }}</div>
        </div>
        <div class="desc-info">
            <div>作者：{{ detail.author }} </div>
            <div v-if="detail.categoryName">分类： {{ detail.categoryName }}</div>
            <van-button plain type="primary" round size="small" @click="follow(detail.isFollowCategory, 2)"
                v-if="detail.isFollowCategory == 1 && detail.categoryName">取消关注</van-button>
            <van-button plain type="primary" round icon="plus" size="small" @click="follow(detail.isFollowCategory, 2)"
                v-else-if="detail.categoryName">关注分类</van-button>
        </div>
        <div v-html="detail.content"></div>
        <img :src="detail.url" v-if="detail.url" style="max-width: 100%;">

        <!-- 评论区Start -->
        <div>
            <h4>用户评论</h4>
            <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
                <van-cell v-for="item in commentList" :key="item.id">
                    <div class="comment-item">{{ item.userName }}：{{ item.content }}
                    </div>
                </van-cell>
            </van-list>
        </div>
        <!-- 评论区End -->

        <!-- 悬浮按钮Start -->
        <div class="fixed-wrap">
            <div class="fixed-icon" @click="like(detail.isLike)">
                <van-icon name="good-job" color="#F56C6C" size="24" v-if="detail.isLike == 1" />
                <van-icon name="good-job-o" size="24" v-else />
            </div>
            <div class="fixed-icon" @click="onComment()">
                <van-icon name="chat-o" size="24" />
            </div>
            <div class="fixed-icon" @click="showShare = true">
                <van-icon name="share-o" size="24" />
            </div>
            <div class="fixed-icon" @click="collect(detail.isCollect)">
                <van-icon name="star" color="#E6A23C" size="24" v-if="detail.isCollect == 1" />
                <van-icon name="star-o" size="24" v-else />
            </div>
            <div class="fixed-icon" @click="followNews(detail.isFollowNews)">
                <van-icon name="eye" color="#E6A23C" size="24" v-if="detail.isFollowNews == 1" />
                <van-icon name="eye-o" size="24" v-else />
            </div>
        </div>
        <!-- 悬浮按钮End -->
        <van-share-sheet v-model:show="showShare" title="立即分享给好友" :options="options" @select="onSelect" />
        <van-popup v-model:show="showComment" position="bottom" :style="{ height: '50%' }"
            :close-on-click-overlay="false" close-on-popstate>
            <van-form @submit="onSubmit">
                <div class="popup-tool">
                    <van-button @click="closeComment">
                        关闭
                    </van-button>
                    <van-button type="primary" native-type="submit" plain>
                        发起评论
                    </van-button>
                </div>
                <van-cell-group inset>
                    <van-field v-model.trim="comment" required type="textarea" name="评论" label="评论" placeholder="请输入"
                        rows="2" maxlength="200" autosize show-word-limit
                        :rules="[{ required: true, message: '请填写评论内容' }]" />
                </van-cell-group>
                <div style="margin: 16px;">

                </div>
            </van-form>
        </van-popup>
    </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue';
import { Toast } from 'vant';
import { useRouter, useRoute } from 'vue-router'
import Api from '@/api/homePage'

const router = useRouter()
const route = useRoute()

//新闻列表
const detail = ref({})

const loading = ref(false);
const finished = ref(false);
const pageNo = ref(1);
const pageSize = ref(99);
const commentList = ref([]);
const userId = localStorage.getItem('userId')

const onLoad = () => {
    // 异步更新数据
    Api.commentList({
        pageNo: pageNo.value,
        pageSize: pageSize.value,
        newsId: route.query.id
    }).then(res => {
        if (pageNo.value === 1) {
            commentList.value = []
        }
        commentList.value.push(...res.data.list);

        if (commentList.value.length >= res.data.count) {
            finished.value = true;
        } else {
            pageNo.value++;
        }
    }).catch(() => {
        // 加载状态结束
        loading.value = false;
        finished.value = true;
    })
};
onMounted(() => {

    //添加浏览记录
    Api.addViews({
        newsId: route.query.id,
        userId: userId
    }).then(res => {
        getDetail()
    })
})

// 获取详情
const getDetail = () => {
    Api.oneDetail(route.query.id).then(res => {
        detail.value = res.data
    })
}

// 分享
const options = [
    { name: '微信', icon: 'wechat' },
    { name: '复制链接', icon: 'link' }
];

const onSelect = (option) => {
    showShare.value = false;
    copyLink()
};
const copyLink = () => {
    // 获取当前链接
    const currentUrl = document.location.href;

    // 创建临时输入框元素
    var tempInput = document.createElement("input");
    tempInput.value = currentUrl;
    document.body.appendChild(tempInput);

    // 选中输入框内容
    tempInput.select();
    tempInput.setSelectionRange(0, 99999); /* For mobile devices */

    try {
        // 执行复制命令
        if (document.execCommand("copy")) {
            Toast("已成功复制链接,请打开应用进行粘贴");
        } else {
            Toast("无法复制链接，请手动复制。");
        }

        // 移除临时输入框元素
        document.body.removeChild(tempInput);
    } catch (err) {
        console.error("复制失败", err);
    }
}

// 点赞
const like = (isLike) => {
    const toast = Toast.loading({
        message: '加载中...',
        forbidClick: true,
    });
    if (isLike == 1) {
        Api.delLike({
            newsId: detail.value.id,
            userId: userId
        }).then(res => {
            getDetail()
            Toast("已取消点赞！");
        }).finally(() => {
            toast.clear()
        })
    } else {
        Api.addLike({
            newsId: detail.value.id,
            userId: userId
        }).then(res => {
            Toast.success("点赞成功！");
            getDetail()
        }).finally(() => {
            toast.clear()
        })
    }
}

// 收藏
const collect = (isCollect) => {
    const toast = Toast.loading({
        message: '加载中...',
        forbidClick: true,
    });
    if (isCollect == 1) {
        Api.delCollect({
            newsId: detail.value.id,
            userId: userId
        }).then(res => {
            Toast("已取消收藏！");
            getDetail()
        }).finally(() => {
            toast.clear()
        })
    } else {
        Api.addCollect({
            newsId: detail.value.id,
            userId: userId
        }).then(res => {
            Toast.success("收藏成功！");
            getDetail()
        }).finally(() => {
            toast.clear()
        })
    }
}

// 分享
const showShare = ref(false);
const onShare = () => {
    showShare.value = true;
}


// 评论
const showComment = ref(false);
const comment = ref('');

const onComment = () => {
    showComment.value = true;
}

const closeComment = () => {
    showComment.value = false;
    comment.value = '';
}
const onSubmit = (values) => {
    if (comment.value) {
        const toast = Toast.loading({
            message: '加载中...',
            forbidClick: true,
        });
        Api.addComment({
            content: comment.value,
            newsId: detail.value.id,
            userId: userId
        }).then(res => {
            Toast.success("评论成功！");
            closeComment()
            pageNo.value = 1;
            onLoad()
        }).finally(() => {
            toast.clear()
        })
    }
};

// 关注新闻
const followNews = (isFollowNews) => {
    const toast = Toast.loading({
        message: '加载中...',
        forbidClick: true,
    });
    if (isFollowNews == 1) {
        Api.delFollow({
            followerId: detail.value.id,
            userId: userId,
            type: 1
        }).then(res => {
            Toast("已取消关注！");
            getDetail()
        }).finally(() => {
            toast.clear()
        })
    } else {
        Api.addFollow({
            followerId: detail.value.id,
            userId: userId,
            type: 1
        }).then(res => {
            Toast.success("关注成功！");
            getDetail()
        }).finally(() => {
            toast.clear()
        })
    }
}
// 关注分类
const follow = (isFollowCategory) => {
    const toast = Toast.loading({
        message: '加载中...',
        forbidClick: true,
    });
    if (isFollowCategory == 1) {
        Api.delFollow({
            followerId: detail.value.categoryId,
            userId: userId,
            type: 2
        }).then(res => {
            Toast("已取消关注！");
            getDetail()
        }).finally(() => {
            toast.clear()
        })
    } else {
        Api.addFollow({
            followerId: detail.value.categoryId,
            userId: userId,
            type: 2
        }).then(res => {
            Toast.success("关注成功！");
            getDetail()
        }).finally(() => {
            toast.clear()
        })
    }
}
</script>

<style lang="scss" scoped>
.container {
    padding: 10px;

    h1 {
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 10px;
    }

    .desc-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
    }

    .fixed-wrap {
        position: fixed;
        top: 60%;
        right: 20px;

        .fixed-icon {
            margin-bottom: 20px;
        }
    }
}

.popup-tool {
    display: flex;
    justify-content: space-between;

    :deep(.van-button) {
        border: none;
    }
}
</style>